const requesturl="https://wxserver.cards120.com"  // 动态后端请求
const requesturlfront="43.136.220.136" // 静态资源加载
new Vue({
    el: '#appzhutiye', // 指定Vue根实例的挂载点
    data: {
        //加载中动画 todo 做到局部加载效果
        ifbianjidonghua:false,
        allCards:[],
        cardshow:false,
        zhutishow:true,

        zhongjianka:{"front":"","back":""},
        ifbianji:false,
        dangqianzhuti:'',
        previewCards:[],
        Menutopic:null,
        draggedCard:null,
        draggedType:'',
        currentFolder:null,
        currentCards:[],
        breadcrumbList: [],
        draggedTopic:null,
        message: 'Hello World from Vue.js!', // 动态数据
        token:"",
        uid:"",
        count: 0, // 另一个动态数据
        topictitle:'测试',
        searchQuery: '', // 新增的搜索框绑定数据
        topiczu: [

        ],
        showRenameDialog: false,
        newName: '',
        itemToRename: null,
        newTopicName: '',


    }, watch:{

    }
    ,
    computed: {
        // 计算属性用于过滤列表
        filteredTopics() {
            if (!this.searchQuery.trim()) {
                return this.topiczu;
            }
            return this.topiczu.filter(item => item.topictitle.includes(this.searchQuery));
        },

        filteredAllCards() {
            if (!this.searchQuery.trim()) {
                return this.allCards;
            }
            return this.allCards.filter(item => item.front.includes(this.searchQuery));
        },
        filteredcurrentCards() {
            if (!this.searchQuery.trim()) {
                return this.currentCards;
            }
            return this.currentCards.filter(item => item.front.includes(this.searchQuery));
        }


    },
    methods: {
        totalCardsView(cardId){
            localStorage.setItem('dangqianzhuti','所有卡片')
            localStorage.setItem('dangqianzhutititle','所有卡片')
            window.location.href = 'cardperform?cardId=' + cardId;
        },
        viewCard(cardId) {

            Swal.fire({
                title: '即将跳转主题详情页',
                text: '',
                icon: 'info',
                confirmButtonText: '好的'
            }).then((result) => {
                if (result.value) {
                    window.location.href = 'cardperform?cardId=' + cardId; // 这里的 '/login' 是你希望跳转到的URL
                }
            });



        },
        switchContent(view) {
            var dropbtn = document.getElementById('dropbtn');
            if(view === 'topics') {
                this.cardshow = false
                this.zhutishow= true
                // 更多的我的主题 HTML 内容
                dropbtn.innerHTML = '我的主题 <i class="arrow-down"></i>';
                this.navigateToFolder(0)
            } else if(view === 'cards') {
                this.cardshow = true
                this.zhutishow= false
                this.loadAndSortCards()
                // 更多的所有卡片 HTML 内容
                dropbtn.innerHTML = '所有卡片 <i class="arrow-down"></i>';
            }
        },
        loadAndSortCards() {
            // 从localStorage读取cards2es数据
            const cards2es = JSON.parse(localStorage.getItem('cards2es')) || {};

            // 从cards2es中读取所有previewCards中的卡片
            let cards = [];
            Object.keys(cards2es).forEach(key => {
                if(key==="所有卡片") return;
                if (cards2es[key].previewCards) {
                    cards = cards.concat(cards2es[key].previewCards);
                }
            });

            // 按照修改时间排序卡片
            cards.sort((a, b) => {
                const aTime = new Date(a.modifiedTime).getTime();
                const bTime = new Date(b.modifiedTime).getTime();
                return bTime - aTime; // 降序排序
            });


            // Object.keys(cards).forEach(key => {
            //     let card = cards[key];
            //     //如果card下的previewCards不存在
            //     if (card.previewCards !== undefined) {
            //         card.previewCards.forEach(previewCard => {
            //             previewCard.id = previewCard.sqlId;
            //
            //
            //
            //
            //         });
            //     }
            // });



            // 更新allCards数据
            this.allCards = [...cards];
        },
        // switchCard(){
        //
        //     this.cardshow = true
        //     this.zhutishow= false
        //     this.loadAndSortCards()
        //
        //
        // },
        // switchZhuti(){
        //
        //     this.cardshow = false
        //     this.zhutishow= true
        //
        // },

        turnCardsZhutiKey(newFolderId,oldFolderId){
            // 假设 oldFolderId 是原始文件夹的 ID，newFolderId 是新文件夹的 ID
            // const oldFolderId = 'old-folder-id';
            // const newFolderId = 'new-folder-id';

            const cardsData = JSON.parse(localStorage.getItem('cards'))|| {};

            if (cardsData && cardsData[oldFolderId]) {
                // 更新文件夹ID和预览卡片的分配

                // 将修改后的卡片列表赋值给新文件夹，同时保留或更新其他相关信息
                cardsData[newFolderId] = {
                    order:"",
                    previewCards: cardsData[oldFolderId].previewCards
                };
                cardsData[oldFolderId].previewCards.map(card => {
                    //保存到推送队列中
                    this.save_xinzengids(card.id)
                    return card;
                });
                // 删除旧的文件夹键
                delete cardsData[oldFolderId];
                // 将更新后的数据保存回 localStorage
                localStorage.setItem('cards', JSON.stringify(cardsData));
                this.cardsTurnCards2ES()

            }

        },
        quxiaobianji(){
            this.ifbianji=!this.ifbianji
        },
        editClick(card){
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 44 ~ card ");
            this.ifbianji=!this.ifbianji
            this.zhongjianka = card
            const externalEditor = this.$refs.fuwenbenbianji;
            tinymce.get(externalEditor.id).setContent(this.zhongjianka.back);
        },
        deleteCard(cardId) {

            Swal.fire({
                title: '确定删除？',
                text: '',
                icon: 'warning',
                confirmButtonText: '确认',
                cancelButtonText: '取消', // 设置取消按钮文本
                showCancelButton: true,   // 显示取消按钮
                reverseButtons: true      // 将取消按钮放在左边，确认按钮放在右边
            }).then((result) => {
                if (result.value) {


                    const index = this.currentCards.findIndex(card => card.id === cardId);
                    if (index !== -1) {
                        this.currentCards.splice(index, 1);
                        this.saveCurrentCardsToLocalStorage();
                        this.cardsTurnCards2ES()
                        this.saveToCenterZhutiXiugai();
                    }else{
                        const index = this.allCards.findIndex(card => card.sqlId === cardId);
                        if (index !== -1) {
                            this.allCards.splice(index, 1);
                        }
                        this.cards2es2cards()
                        //    如果找不到，就从allcards中找就行了，然后删除allcards中的
                    }
                    let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];
                    shanchu.push(cardId);
                    localStorage.setItem('shanchu', JSON.stringify(shanchu));
                    this.saveToCenter()

                } else if (result.dismiss === Swal.DismissReason.cancel) {

                }



            });




        },
        saveToCenterZhutiXiugai() {
            let zhuti = localStorage.getItem('zhuti') ? JSON.parse(localStorage.getItem('zhuti')) : {};
            const dangqianzhuti = localStorage.getItem('dangqianzhuti');
            const newOrder = this.previewCards.map(card => card.id).join(',');
            const newOrderName = this.previewCards.map(card => card.front).join(',').replace(/<\/?p>/g, "");

            if (zhuti && zhuti.topics) {
                const updateOrderAndEditTime = (topics) => {
                    topics.forEach(topic => {
                        if (topic.topictitle === dangqianzhuti) {
                            topic.order = newOrder;
                            topic.newOrderName = newOrderName;
                            topic.edittime = new Date().toISOString().slice(0, 19).replace('T', ' ');

                            if (topic.children && topic.children.length > 0) {
                                updateOrderAndEditTime(topic.children); // 递归处理子节点
                            }
                        } else if (topic.children && topic.children.length > 0) {
                            updateOrderAndEditTime(topic.children); // 递归处理其他层级
                        }
                    });
                };

                updateOrderAndEditTime(zhuti.topics);
                localStorage.setItem('zhuti', JSON.stringify(zhuti));
            }
        },
        cardsTurnCards2ES: function () {
            const cards1 = JSON.parse(localStorage.getItem('cards'));

            if (cards1 && typeof cards1 === 'object') {
                let latestUpdateTime = new Date(0); // 设置初始最早的时间
                let latestCardId = null;
                Object.keys(cards1).forEach(key => {
                    let card = cards1[key];
                    //如果card下的previewCards不存在
                    if (card.previewCards !== undefined) {
                        card.previewCards.forEach(previewCard => {
                            if ('front' in previewCard) previewCard.front = key + '：' + previewCard.front;
                            ;
                            if ('mark' in previewCard) {
                                previewCard.known = previewCard.mark;
                                delete previewCard.mark;
                            }
                            ;
                            if ('id' in previewCard) {
                                previewCard.sqlId = previewCard.id;
                                delete previewCard.id;
                            }
                            ;
                            if ('time' in previewCard) {
                                previewCard.createtime = previewCard.time;
                                delete previewCard.time;
                            }
                            ;
                            if ('lastmodifieddate' in previewCard) {
                                previewCard.lastmodifieddate = previewCard.lastmodifieddate;
                                delete previewCard.updatetime;
                                delete previewCard.icon;
                                delete previewCard.size;
                            }
                            ;previewCard.uid = this.uid;
                            previewCard.type = 1;


                            // 更新最近修改的卡片ID
                            const currentUpdateTime = new Date(previewCard.lastmodifieddate);
                            if (currentUpdateTime > latestUpdateTime) {
                                latestUpdateTime = currentUpdateTime;
                                latestCardId = previewCard.sqlId;
                            }

                        });
                    }
                });
                console.log("🚀 ~ file: cardperform.html ~ line 428 ~ latestCardId: ", latestCardId);
                // this.save_xinzengids(latestCardId) todo 有争议需要讨论
                localStorage.setItem('cards2es', JSON.stringify(cards1))
                this.loadAndSortCards()
            }
        }, saveToCenter() {

            this.previewCards =  [...this.currentCards]
            let topic = {order: '', previewCards: []};
            topic.previewCards = [...this.previewCards];
            topic.order = this.previewCards.map(card => card.id).join(',');
            this.saveToCenterZhutiXiugai();
            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
            cards[this.dangqianzhuti] = topic;
            localStorage.setItem('cards', JSON.stringify(cards));
            this.cardsTurnCards2ES();


        },
        handleBreadcrumbDrop(event) {
            event.preventDefault();
            if(this.draggedType==='card'){

                const topicId = event.target.getAttribute('foldId');
                //    找到localstorage中的名为cards的对象中对应字典key为 localstorage中 dangqianzhuti的值的previewcards对象，将previewcards中的和this.draggedCard的id相等的元素进行剔除并找到
                this.draggedFromCardToFold(event,topicId,event.target.textContent);
                this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);
                this.save_xinzengids(this.draggedCard.id)
            }else{

                const topic = this.draggedTopic;
                console.log("🚀 ~ file: car dzhuye-vue.js ~ line 36 ~ topic: ",topic);
                const topicId = event.target.getAttribute('foldId');
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 37 ~ topicId: ",topicId);
                // const draggedTopicId = event.dataTransfer.getData("text/plain");
                this.moveTopicToBreadcrumb(topic.topicid,topicId);
            }
            this.cardsTurnCards2ES()
            //    只更新时间
        },
        moveTopicToBreadcrumb(draggedTopicId, targetTopicId) {
            let draggedTopic = null;

            // 定义一个递归函数来遍历并尝试移除topic
            function removeTopicRecursive(topicList, id) {
                for (let i = 0; i < topicList.length; i++) {
                    if (topicList[i].topicid === id) {
                        // 找到对应的topic，从数组中移除并返回该topic
                        draggedTopic = topicList.splice(i, 1)[0];
                        draggedTopic.edittime =new Date().toISOString().slice(0, 19).replace('T', ' ')
                        return true; // 返回true表示找到并移除了topic
                    }
                    // 如果当前topic有children，递归检查children
                    if (topicList[i].children && topicList[i].children.length > 0) {
                        if (removeTopicRecursive(topicList[i].children, id)) {
                            return true; // 在children中找到并移除了topic
                        }
                    }
                }
                return false; // 没有找到对应的topic
            }

            // 定义一个递归函数来找到目标topic，并将被拖拽的topic插入到其children中
            function insertTopicRecursive(topicList, targetId, topicToInsert) {
                for (let topic of topicList) {
                    if (topic.topicid === targetId) {
                        // 找到目标topic，将被拖拽的topic插入到其children中
                        if (!topic.children) {
                            topic.children = []; // 确保children数组存在
                        }
                        topic.children.unshift(topicToInsert);
                        return true;
                    }
                    // 递归搜索children
                    if (topic.children && topic.children.length > 0) {
                        if (insertTopicRecursive(topic.children, targetId, topicToInsert)) {
                            return true;
                        }
                    }
                }
                return false;
            }

            // 从当前主题列表移除被拖拽的topic
            removeTopicRecursive(this.breadcrumbList, draggedTopicId);

            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 87 ~ draggedTopic: ",draggedTopic);
            // 如果被拖拽的topic成功移除，尝试将其插入到目标位置
            if (draggedTopic) {
                const ifInsert = insertTopicRecursive(this.breadcrumbList, targetTopicId, draggedTopic);
                // todo localstorage.set
                this.saveTopicsToLocalStorage();
                localStorage.setItem('maxEditTimeZhuti', 0);
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 91 ~ ifInsert: ",ifInsert);
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 92 ~ this.breadcrumbList.length: ",this.breadcrumbList.length);
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 93 ~ this.breadcrumbList: ",this.breadcrumbList);

            }
        },

        handleDrop(crumb, event) {
            event.preventDefault();
            // 获取被拖拽文件夹的ID
            const folderId = event.dataTransfer.getData("text/plain");
            // 根据ID和目标面包屑执行移动逻辑
            this.moveFolderTo(folderId, crumb.id);
        },
        removeFromBreadcrumb(topicId) {
            // 定义一个递归函数来遍历并尝试移除topic
            function removeTopicRecursive(topicList, id) {
                for (let i = 0; i < topicList.length; i++) {
                    if (topicList[i].topicid === id) {
                        // 找到对应的topic，从数组中移除
                        topicList.splice(i, 1);
                        return true; // 返回true表示找到并移除了topic
                    }
                    // 如果当前topic有children，递归检查children
                    if (topicList[i].children && topicList[i].children.length > 0) {
                        if (removeTopicRecursive(topicList[i].children, id)) {
                            return true; // 在children中找到并移除了topic
                        }
                    }
                }
                return false; // 没有找到对应的topic
            }

            // 从breadcrumbList的每个层级尝试移除topic
            removeTopicRecursive(this.breadcrumbList, topicId);
        },
        removeBreadcrumbTopic(removeTopicId) {
            // 寻找要删除的topic在breadcrumbList中的索引
            const index = this.breadcrumbList.findIndex(topic => topic.topicid === removeTopicId);

            // 如果找到了，从breadcrumbList中移除
            if (index !== -1) {
                this.breadcrumbList.splice(index, 1);
            }

            // 此处应有代码以适当方式更新组件状态或重新渲染
        },
        // 从localStorage读取zhuti数据
        fetchZhutiFromLocalStorage() {
            const zhutiData = localStorage.getItem('zhuti');
            if (zhutiData) {
                return JSON.parse(zhutiData);
            }
            return null;// 或返回默认值
        },
        resetToRoot() {

            // 假设 topiczu 是根目录的数据
            // 如果根目录有特定的数据结构，请调整此逻辑
            if(this.breadcrumbList.length==0){
                this.fetchAndStoreZhuti1().then(() => {
                    this.pageInit();
                    this.reloadWebflowJs(); // 重新加载 webflow.js
                });
            }

        },
        getContentFromEditor() {
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 277 ~ getContentFromEditor: ");
            this.previewCards=[...this.currentCards]
            var textarea = document.getElementById('fronttextarea');
            var fronttextarea = textarea.value;
            var editor = tinymce.get('myTextarea');
            var backtextarea = editor.getContent();
            var cardIndex = ""
            let bulkBody = '';
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
            const day = String(currentDate.getDate()).padStart(2, '0');
            const hours = String(currentDate.getHours()).padStart(2, '0');
            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
            const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            //特殊逻辑单独发送
            if(this.zhongjianka.id===undefined){
                cardIndex = this.allCards.findIndex(card => card.sqlId === this.zhongjianka.sqlId);
                if (cardIndex!=-1) {


                    this.zhongjianka.lastmodifieddate = currentTime;
                    this.zhongjianka.front = fronttextarea
                    this.zhongjianka.back = backtextarea

                    var card = this.zhongjianka

                    //
                    console.log("🚀 ~ file: cardperform.html ~ line 449 ~ card: ", card);
                    // 从ids字符数组中拿到待新增的数组内容，

                    bulkBody += JSON.stringify({index: {_index: 'users', _type: '_doc', _id: card.sqlId}}) + '\n';
                    bulkBody += JSON.stringify(card) + '\n';

                    if (bulkBody) {
                        console.log("🚀 ~ file: cardperform.html ~ line 459 ~ bulkBody: ", bulkBody);
                        axios.post(requesturl+'/proxy-bulk', bulkBody, {
                            headers: {'Content-Type': 'application/x-ndjson'}
                        }).then(response => {
                                console.log('Bulk operation successfully executed', response.data);
                                // 从xinzengids数组中移除已新增的IDs
                                // 成功之后本地更新
                                this.allCards[cardIndex] = this.zhongjianka
                                //todo 找到localstorage中的cards2es，遍历cards2es中的key下的previewCards找到previewCards下sqlId为this.zhongjianka.sqlId的卡片然后将这张卡片内容重置为this.zhongjianka
                                // 获取localStorage中的cards2es数据
                                const cards2es = JSON.parse(localStorage.getItem('cards2es'));

                                if (cards2es && typeof cards2es === 'object') {
                                    // 遍历所有主题键
                                    Object.keys(cards2es).forEach(topicKey => {
                                        const topic = cards2es[topicKey];
                                        // 遍历previewCards数组，找到对应的卡片并更新内容
                                        topic.previewCards.forEach(card => {
                                            if (card.sqlId === this.zhongjianka.sqlId) {
                                                // 更新卡片内容为当前编辑中的卡片内容
                                                card.front = this.zhongjianka.front;
                                                card.back = this.zhongjianka.back;
                                                card.updatetime = this.zhongjianka.updatetime;
                                            }
                                        });
                                    });

                                    // 将更新后的数据写回localStorage
                                    localStorage.setItem('cards2es', JSON.stringify(cards2es));
                                }
                                this.cards2es2cards()
                            }
                        ).catch(error => console.error('Failed to execute bulk operation', error));
                    }
                }else {
                    alert("没有找到待更新卡片")
                }
                return ;



            }else{
                cardIndex = this.previewCards.findIndex(card => card.id === this.zhongjianka.id);
            }
            if (cardIndex !== -1) {

                this.previewCards[cardIndex].back = backtextarea;
                this.previewCards[cardIndex].front = fronttextarea;
                this.previewCards[cardIndex].updatetime = currentTime;
                this.currentCards=[...this.previewCards]
                this.saveCurrentCardsToLocalStorage();
                Swal.fire({
                    toast: true,                   // 启用toast模式
                    position: 'top-end',           // 设置toast出现的位置
                    showConfirmButton: false,      // 不显示确认按钮
                    timer: 3000,                   // 设置显示时间为1000毫秒（1秒）
                    title: '更新完成',
                    icon: 'success',               // 显示成功图标
                })
                this.saveToCenter()
                this.save_xinzengids(this.zhongjianka.id)
            } else alert("未找到要更新的卡片");
        },
        checkVip(){
            // 获取当前日期
            const currentDate = new Date();

// 从 localStorage 中获取 'zhuti' 数据
            const zhutiData = localStorage.getItem('zhuti');
            if (zhutiData) {
                const zhuti = JSON.parse(zhutiData);
                const vipDate = zhuti.vipdate ? new Date(zhuti.vipdate) : new Date(new Date().setDate(currentDate.getDate() - 1));


                // 检查当前日期是否大于 vipdate
                if (currentDate > vipDate) {
                    // 从 localStorage 获取 'cards' 数据
                    const cardsData = localStorage.getItem('cards');
                    if (cardsData) {
                        const cards = JSON.parse(cardsData);

                        // 检查是否存在键为 '所有卡片' 的数组
                        if (cards['所有卡片']) {
                            const allCardsLength = cards['所有卡片'].previewCards.length;
                            console.log('所有卡片的数组长度:', allCardsLength);
                            if (allCardsLength > 20) {
                                console.log('所有卡片的数组长度大于20，不能继续执行。');
                                return false; // 使用 return 中断执行
                            }
                            // 在这里执行提交逻辑
                            // 例如，可以是发送数据到服务器或者其他处理
                            // ...
                        } else {
                            console.log('没有找到键为‘所有卡片’的数组');
                        }
                    } else {
                        console.log('无法找到 cards 数据');
                    }
                } else {
                    console.log('当前日期不大于 VIP 日期');
                }
            } else {
                console.log('无法找到 zhuti 数据');
            }
            return true
        },
        getContentFromEditorXinZeng() {
            if(!this.checkVip()){
                alert("非会员只能创建20张自定义卡，请前往个人中心升级会员")
                return;
            }
            var textarea = document.getElementById('fronttextareaxinzeng');
            var fronttextarea = textarea.value;
            var editor = tinymce.get('myTextareaxinzeng');
            var backtextarea = editor.getContent();
            const cardIndex = this.currentCards.findIndex(card => card.front === fronttextarea);
            if (cardIndex === -1) {
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                const hours = String(currentDate.getHours()).padStart(2, '0');
                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                var id = this.uid + new Date().getTime().toString();
                const newCard = {
                    id: id,
                    front: fronttextarea,
                    back: backtextarea,
                    time: currentTime,
                    updatetime: currentTime,
                    mark: 0
                };
                this.currentCards.unshift(newCard);
                //将newCard放到 localstorage的cards对应的topic下的preview中

                this.saveCurrentCardsToLocalStorage();
                Swal.fire({
                    toast: true,                   // 启用toast模式
                    position: 'top-end',           // 设置toast出现的位置
                    showConfirmButton: false,      // 不显示确认按钮
                    timer: 3000,                   // 设置显示时间为1000毫秒（1秒）
                    title: '新增完成',
                    icon: 'success',               // 显示成功图标
                })
                this.saveToCenter()
                this.save_xinzengids(id)
            } else alert("卡片名称冲突");
        },
        saveCurrentCardsToLocalStorage() {
            // 假设cards对象已经存在于localStorage中，并且我们是在特定的主题下添加新卡片
            let cards = JSON.parse(localStorage.getItem('cards')) || {};
            const currentTopic = localStorage.getItem("dangqianzhuti"); // 当前主题名称，需要根据实际代码逻辑定义
            // 确保当前主题下的previewCards数组存在
            if (!cards[currentTopic]) {
                cards[currentTopic] = { previewCards: [] };
            }
            // 将当前卡片列表赋值给当前主题下的previewCards
            cards[currentTopic].previewCards = this.currentCards;
            // 更新localStorage中的cards对象
            localStorage.setItem('cards', JSON.stringify(cards));
        },
        qingkongxinzengkuang() {
            document.getElementById("fronttextareaxinzeng").value = "";
            var editor = tinymce.get('myTextareaxinzeng');
            if (editor) editor.setContent('');
        },
        save_xinzengids(id) {
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 394 ~ save_xinzengids: ");
            var xinzengids = localStorage.getItem('xinzengids');
            if (xinzengids) {
                xinzengids = JSON.parse(xinzengids);
                //push的时候添加去重逻辑
                if (xinzengids.indexOf(id) === -1)
                    xinzengids.push(id);
            } else xinzengids = [id];
            localStorage.setItem('xinzengids', JSON.stringify(xinzengids));
        },
        getOrderFromZhuti(topicName) {
            // 从localStorage中获取zhuti数据
            const zhutiData = JSON.parse(localStorage.getItem('zhuti') || '{}');
            // 递归查找与topicName匹配的主题，并返回其order
            const findOrder = (topics) => {
                for (const topic of topics) {
                    if (topic.topicname === topicName && topic.order) {
                        return topic.order.split(',');
                    }
                    if (topic.children) {
                        const result = findOrder(topic.children);
                        if (result) return result;
                    }
                }
                return null;
            };
            return findOrder(zhutiData.topics || []);
        },
        fetchCardsFromLocalStorage(topicName) {
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 376 ~ topicName: ",topicName);
            // 从localStorage获取cards数据
            const cardsData = JSON.parse(localStorage.getItem('cards') || '{}');
            // 检索与主题名称匹配的卡片列表
            const cards = cardsData[topicName] ? cardsData[topicName].previewCards : [];
            //todo 这里需要根据zhuti中的order进行排序
            // 获取order
            const order = this.getOrderFromZhuti(topicName);
            if (order) {
                // 根据order排序cards
                cards.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
            }

            //每一次order都从这里取就行了，不用从cards取order,不过要用id来匹配

            // 更新currentCards属性以反映新的卡片列表
            this.currentCards = cards;
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 383 ~ this.currentCards: ",this.currentCards);
            this.breadInit()
        },
        navigateToFolder(index) {
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 186 ~ navigateToFolder: ");
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 85 ~ index: ",index);
            // 导航到选中的面包屑索引位置
            this.breadcrumbList = this.breadcrumbList.slice(0, index + 1);
            this.currentFolder = this.breadcrumbList[index];
            this.topiczu = this.currentFolder.children || [];


            localStorage.setItem('dangqianzhuti', this.currentFolder.topictitle);
            localStorage.setItem('dangqianzhutititle', this.currentFolder.topictitle);
            this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);
            // this.reloadWebflowJs(); // 重新加载 webflow.js
            this.dangqianzhuti = localStorage.getItem('dangqianzhuti');

        },
        childrenTopic(topic){
            this.currentFolder = topic;
            // 更新面包屑导航数据
            this.breadcrumbList.push(topic);
            // 更新页面中展示的 topic 数据为当前文件夹的子节点
            this.topiczu = topic.children || [];
            this.reloadWebflowJs(); // 重新加载 webflow.js
            localStorage.setItem('dangqianzhuti', topic.topictitle);
            localStorage.setItem('dangqianzhutititle', topic.topictitle);
            this.fetchCardsFromLocalStorage(topic.topictitle);
            this.dangqianzhuti = localStorage.getItem('dangqianzhuti');
        },
        draggedFromCardToFold: function (event,topicId,breadTitle) {
            // Retrieve the current theme from localStorage
            const currentThemeId = localStorage.getItem('dangqianzhuti');
            // Assuming cards are stored in an array under each theme's 'previewCards' key in localStorage
            const themes = JSON.parse(localStorage.getItem('cards')) || {};
            const currentTheme = themes[currentThemeId];


            const targetTopicIndex = this.topiczu.findIndex(topic => topic.topicid === topicId);
            var targetTopicTitle = ""
            if(targetTopicIndex===-1){
                //没有拖放到正确位置
                if(breadTitle===''){
                    return ;
                }
                targetTopicTitle = breadTitle
            }else{
                targetTopicTitle = this.topiczu[targetTopicIndex].topictitle
            }
            //拽到面包屑导航的当前文件夹，则内容不变,将位置提前
            // 拽到面包屑导航的当前文件夹，则内容不变,位置提前
            if (targetTopicTitle === currentThemeId) {
                // 找到拖拽的卡片在当前主题previewCards数组中的位置
                const cardIndex = currentTheme.previewCards.findIndex(card => card.id === this.draggedCard.id);
                if (cardIndex > -1) {
                    // 从数组中移除该卡片
                    currentTheme.previewCards.splice(cardIndex, 1);
                    // 将卡片重新插入到数组的开头
                    currentTheme.previewCards.unshift(this.draggedCard);
                }
                this.draggedCard.lastmodifieddate = new Date().toISOString().slice(0, 19).replace('T', ' ');
                // 不需要进一步处理，直接更新localStorage并返回
                localStorage.setItem('cards', JSON.stringify(themes));
                return;
            }

            const currentThemeDragTo = themes[targetTopicTitle];
            if (!currentThemeDragTo) {
                themes[targetTopicTitle] = {'order': '', 'previewCards': []}
            }
            this.draggedCard.lastmodifieddate = new Date().toISOString().slice(0, 19).replace('T', ' ')
            // 假设 themes 是你的对象，targetTopicTitle 是你要操作的目标主题
            if (!themes[targetTopicTitle]) {
                // 如果 themes 对象中不存在 targetTopicTitle，先初始化这个键值对
                Vue.set(themes, targetTopicTitle, { previewCards: [] });
            } else if (!themes[targetTopicTitle].previewCards) {
                // 如果 themes[targetTopicTitle] 存在但没有 previewCards 属性，就初始化为数组
                Vue.set(themes[targetTopicTitle], 'previewCards', []);
            }
            themes[targetTopicTitle].previewCards.unshift(this.draggedCard)
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 222 ~ themes: ",themes);



            if (currentTheme && currentTheme.previewCards) {
                // Filter out the card that matches this.draggedCard's ID
                const updatedPreviewCards = currentTheme.previewCards.filter(card => card.id !== this.draggedCard.id);

                // Update the theme with the new list of previewCards
                currentTheme.previewCards = updatedPreviewCards;
                themes[currentThemeId] = currentTheme;
                // Update localStorage
            }







            localStorage.setItem('cards', JSON.stringify(themes));

        },
        dropTopic(event) {


            event.preventDefault();

            if(this.draggedType==='card'){
                const topicId = event.target.getAttribute('id');
                this.draggedFromCardToFold(event,topicId,'');
                this.save_xinzengids(this.draggedCard.id)
                // this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);
                // const zhongjiankaExists = this.currentCards.some(card => card.id === this.draggedCard.id);
                // if (!zhongjiankaExists ) {
                // //    已经添加过去了，这时候只需要保存到push2es就好了
                //
                // }

            }else{

                const topic = this.draggedTopic;
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 60 ~ topic: ",topic);
                const topicId = event.target.getAttribute('id');
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 36 ~ event.target: ",event.target);
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 59 ~ topicId: ",topicId);
                // 在 topiczu 中查找对应的 topicId
                const targetTopicIndex = this.topiczu.findIndex(topic => topic.topicid === topicId);
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 40 ~ targetTopicIndex: ",targetTopicIndex);

                if (targetTopicIndex !== -1 && topicId!==topic.topicid) {
                    const targetTopic = this.topiczu[targetTopicIndex];
                    // 将 draggedTopic 作为 targetTopic 的子节点放入其中
                    if (!targetTopic.children) {
                        // 如果目标 topic 还没有 children 属性，则创建一个空数组
                        targetTopic.children = [];
                    }
                    // 将 draggedTopic 添加到 targetTopic 的 children 数组中
                    targetTopic.children.unshift(this.draggedTopic);

                    // 更新修改后的 targetTopic 到 this.topiczu 中
                    this.$set(this.topiczu, targetTopicIndex, targetTopic);

                    // 从 this.topiczu 中移除拖拽的 topic
                    const draggedTopicIndex = this.topiczu.findIndex(topic => topic.topicid === this.draggedTopic.topicid);
                    if (draggedTopicIndex !== -1) {
                        this.topiczu.splice(draggedTopicIndex, 1);
                    }
                    // 在这里可以进一步处理将 draggedTopic 放入 targetTopic 的逻辑
                    console.log(`Dropped topic: ${this.draggedTopic} into topic with ID: ${topicId}`);
                    this.saveTopicsToLocalStorage();
                    //这种没有时间状态的保存
                    localStorage.setItem('maxEditTimeZhuti', 0);

                } else {
                    console.log(`Failed to find topic with ID: ${topicId}`);
                }
                console.log("🚀 ~ file: cardzhuye-vue.js ~ line 61 ~ this.topiczu: ",this.topiczu);
                // 执行将拖拽的数据放到下一级目录中的逻辑,拖拽到下一级目录
            }
            //在这里重新渲染的从currentCards重新拉的过程
            this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);
            //    重新保留到cards2es直接复制就行了
            this.cardsTurnCards2ES()
        },
        dragStart(event, item,type) {
            this.draggedType = type;
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 31 ~ item: ",item);
            // 将拖拽的数据传递给拖拽目标
            // 拖拽目标数据打印，打印拖拽目标上的item内容
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 33 ~ dragStart ~ event: ",event);
            if (type === 'card') {
                this.draggedCard = item;
            } else {
                this.draggedTopic = item; // Assuming 'draggedTopic' is used for folders
            }

        },
        saveTopicsToLocalStorage() {
            // 创建一个新的 JSON 对象
            let storedData = localStorage.getItem('zhuti');
            if (storedData) {
                // 将存储的字符串解析为 JSON 对象
                let json = JSON.parse(storedData);

                // 更新 topics 和 order 属性
                json.topics = this.breadcrumbList[0].children;
                json.order = this.breadcrumbList[0].children.map(topic => topic.topicid).join(',');

                // 将更新后的 JSON 对象转换为字符串并重新保存到 localStorage
                localStorage.setItem('zhuti', JSON.stringify(json));
            } else {
                // 如果 localStorage 中没有 'zhuti'，则按照原来的逻辑创建新的数据项
                let json = {
                    topics: this.breadcrumbList[0].children,
                    order: this.breadcrumbList[0].children.map(topic => topic.topicid).join(',')
                };
                localStorage.setItem('zhuti', JSON.stringify(json));
            }
        },
        showAlert() {
            alert('Hello from Vue.js!');
        },
        incrementCount() {
            this.count++;
        },
        removeTopic(topic) {
            alert("数据无价，删除主题文件夹不删除文件，如果删除文件请到全局卡片删除")
            // 更新topics数组
            this.topiczu = this.topiczu.filter(item => item.topictitle !== topic.topictitle);
            this.removeFromBreadcrumb(topic.topicid)
            this.saveTopicsToLocalStorage();

            // 直接从localStorage中获取必要的数据
            const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || { "topics": [] };
            const uid = localStorage.getItem('uid');

            // 不能删除，还是重置为0，检测到为0就会重新保存
            localStorage.setItem('maxEditTimeZhuti', 0);

            // 如果topics数组为空，则提交覆盖远程数据
            if (localZhuti.topics.length === 0 && uid) {
                const data = {
                    id: uid,
                    zhuti: JSON.stringify(localZhuti) // 确保提交的是字符串格式的JSON
                };

                axios.post(`${requesturl}/proxy-user-order-cud`, data).then(response => {
                    console.log('Data successfully saved to Elasticsearch', response.data);
                    // 更新maxEditTimeZhuti等逻辑（如果有的话）
                }).catch(error => {
                    console.error('Failed to save data to Elasticsearch', error);
                });
            }
        }
        ,
        openRenameDialog(item) {
            //如果有新增或者编辑则不能修改
            let xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
            if (xinzengids.length>0) {
                alert('未同步完成，请稍后操作');
                return;
            }
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 602 ~ item: ",item);
            this.showRenameDialog = true;
            this.newName = item.topictitle;
            this.itemToRename = item;
        },
        cancelRename() {
            this.showRenameDialog = false;
            this.newName = '';
            this.itemToRename = null;
        },
        renameTopic() {
            // 检查新名称是否已存在
            if (this.topiczu.some(item => item.topictitle === this.newName)) {
                alert('This name already exists.');
                return;
            }



            // 检查是否有选中的项目进行重命名
            if (this.itemToRename) {
                this.turnCardsZhutiKey(this.newName,this.itemToRename.topictitle)

                // 获取当前日期和时间
                const now = new Date();
                const datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
                // 更新 topictitle 和 edittime
                this.itemToRename.topictitle = this.newName;
                this.itemToRename.topicname = this.newName;
                this.itemToRename.edittime = datetime;
            }
            // 关闭重命名对话框并重置相关数据
            this.cancelRename();
            this.saveTopicsToLocalStorage()
            localStorage.removeItem("maxEditTimeZhuti")
        },
        addNewTopic1() {
            // 检查newTopicName是否为空
            if (!this.newTopicName.trim()) {
                alert('请输入主题名称。');
                return;
            }
            // 检查主题名称是否已存在
            if (this.topiczu.some(item => item.topictitle === this.newTopicName)) {
                alert('此名称已存在。');
                return;
            }
            // 获取当前日期和时间
            const now = new Date();
            const datetime = now.toISOString().slice(0, 19).replace('T', ' ');
            // 生成唯一的 topicid
            const topicid = this.uid + Date.now().toString();
            // 添加新主题
            this.topiczu.unshift({
                topicid: topicid,
                topictitle: this.newTopicName,
                edittime: datetime,
                createtime: datetime,
                topicname: this.newTopicName
            });
            //同时添加到面包导航对应位置中

            // 重置输入框并关闭弹窗
            alert('添加成功');
            this.newTopicName = '';
            this.saveTopicsToLocalStorage();
//    重新渲染webflow动态效果
            this.reloadWebflowJs()

        },
        addNewTopic() {
            if (!this.newTopicName.trim()) {
                alert('请输入主题名称。');
                return;
            }
            if (this.topiczu.some(item => item.topictitle === this.newTopicName)) {
                alert('此名称已存在。');
                return;
            }
            const now = new Date();
            const datetime = now.toISOString().slice(0, 19).replace('T', ' ');
            const topicid = this.uid + Date.now().toString();
            const newTopic = {
                topicid: topicid,
                topictitle: this.newTopicName,
                edittime: datetime,
                createtime: datetime,
                order:'',
                newOrderName:'',
                topicname: this.newTopicName,
                children: []
            };

            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 276 ~ this.currentFolder: ",this.currentFolder);
            // 判断当前是否有选中的父文件夹
            if (this.currentFolder) {
                // 如果有，将新主题添加到该文件夹的子主题中
                if (!this.currentFolder.children) {
                    this.currentFolder.children = [];
                }
                this.currentFolder.children.unshift(newTopic);
                this.topiczu = this.currentFolder.children;
            } else {
                this.topiczu.unshift(newTopic);
            }
// 如果没有，添加到根目录

            this.newTopicName = ''; // 重置输入框
            this.saveTopicsToLocalStorage(); // 保存更改到本地存储
            localStorage.setItem('maxEditTimeZhuti', '0');

            this.saveToCenter()

            this.reloadWebflowJs(); // 重新渲染webflow动态效果
        },
        goToCardPerform(value) {
            // 将值保存到 localStorage
            localStorage.setItem('dangqianzhuti', value.topicname);
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 809 ~ value.topicname: ",value.topicname);
            localStorage.setItem('dangqianzhutititle', value.topicname);
            // 跳转到 cardperform 页面
            window.location.href = '/cardperform';
        }//
        ,
        sortByCreateTime() {
            console.log(this.currentCards)
            // 按创建时间升序排序
            this.topiczu.sort((a, b) => {
                return new Date(b.createtime) - new Date(a.createtime);
            });
            this.currentCards.sort((a, b) => {
                return new Date(b.time) - new Date(a.time);
            });
            this.allCards.sort((a, b) => {
                return new Date(b.createtime) - new Date(a.createtime);
            });

        },
        sortByEditTime() {
            // 按修改时间升序排序
            this.topiczu.sort((a, b) => {
                return new Date(b.edittime) - new Date(a.edittime);
            });
            this.currentCards.sort((a, b) => {
                return new Date(b.updatetime) - new Date(a.updatetime);
            });
            this.allCards.sort((a, b) => {
                return new Date(b.lastmodifieddate) - new Date(a.lastmodifieddate);
            });
        },
        sortByOrderFromLocalStorage() {
            console.log("==sortByOrderFromLocalStorage==")
            console.log(this.topiczu)
            // 从 localStorage 中获取 zhuti 数据
            const zhutiData = localStorage.getItem('zhuti');
            if (zhutiData) {
                try {
                    const parsedData = JSON.parse(zhutiData);
                    if (parsedData && parsedData.order) {
                        // 获取 order 中的 topicid 顺序
                        const order = parsedData.order.split(',');
                        // 根据 order 数组的顺序重排 topiczu ，但是topiczu没有初始化所以这里无效,找到这个
                        this.topiczu.sort((a, b) => {
                            return order.indexOf(a.topicid) - order.indexOf(b.topicid);
                        });
                    }
                } catch (e) {
                    console.error('Error parsing zhuti from localStorage:', e);
                    // 错误处理逻辑
                }
            }
        },
        fetchAndStoreZhuti1() {
            return new Promise((resolve, reject) => {
                const query = {
                    query: {
                        bool: {
                            must: [{match: {id: localStorage.getItem('uid')}}]
                        }
                    }, size: 100
                };

                axios.post(requesturl+'/proxy-user-order-r', query)
                    .then(async response => {
                        let maxEditTimeLocalZhuti = 0;
                        if (response.data.hits.hits.length > 0) {
                            const zhutiData = JSON.parse(response.data.hits.hits[0]._source.zhuti);
                            console.log("zhutiData: ", zhutiData);

                            const maxEditTimeZhutiData = Math.max(...zhutiData.topics.map(topic => new Date(topic.edittime).getTime()));

                            const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
                            maxEditTimeLocalZhuti = localZhuti.topics.length > 0
                                ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
                                : 0;

                            if (maxEditTimeZhutiData > maxEditTimeLocalZhuti) {
                                localStorage.setItem('zhuti', JSON.stringify(zhutiData));
                            }
                            //将maxEditTimeZhutiData保存到localStorage中，以便下次比较
                            localStorage.setItem('maxEditTimeZhuti', maxEditTimeZhutiData);
                            resolve(); // 成功解决Promise
                        } else {
                            localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
                            console.log('未找到匹配的数据');
                            resolve(); // 未找到数据也视为解决Promise
                        }
                    })
                    .catch(error => {
                        console.error('查询失败:', error);
                        reject(error); // 发生错误时拒绝Promise
                    });


            });
        },
        initSuoyouKapian() {
            // 创建一个虚拟主题名称，用于表示所有卡片
            const virtualTopicName = "所有卡片";

            // 尝试从localStorage中获取cards
            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};

            // 创建一个新的previewCards数组，用于存放所有卡片
            let allPreviewCards = [];

            // 遍历cards中的每个主题，将其previewCards合并到allPreviewCards中1
            Object.keys(cards).forEach(key => {
                if (key === "所有卡片") return;
                const topic = cards[key];
                if (topic && topic.previewCards) {
                    allPreviewCards = allPreviewCards.concat(topic.previewCards);
                }
            });

            // 创建虚拟主题，并将所有卡片的数组赋值给它
            const virtualTopic = {
                order: '', // 虚拟主题可以没有顺序
                previewCards: allPreviewCards
            };

            // 将虚拟主题添加到cards对象中
            cards[virtualTopicName] = virtualTopic;

            // 更新localStorage
            this.saveTopicNameToCards(cards)
            localStorage.setItem('cards', JSON.stringify(cards));
        },
        pageInit(){
            this.initSuoyouKapian()
            const uid = localStorage.getItem('uid');
            if (uid) {this.uid=uid} else { alert("请登录")}
            // 触发自定义排序
            this.sortByOrderFromLocalStorage()
            // 尝试从 localStorage 中获取 zhuti 键的值
            const zhutiData = localStorage.getItem('zhuti');
            // 检查是否存在 zhuti 数据
            if (zhutiData) {
                try {
                    // 解析存储的 JSON 字符串
                    const parsedData = JSON.parse(zhutiData);
                    // 检查解析出的数据是否包含 topics 键
                    if (parsedData && parsedData.topics) {
                        // 将 topics 键的值赋给 topiczu
                        this.topiczu = parsedData.topics;
                    }
                } catch (e) {
                    console.error('Error parsing zhuti from localStorage:', e);
                    // 处理错误，例如提供默认值或显示错误消息
                }
            }
            //当初始化为空时


            //todo 初始化的时候将zhuti中的 order赋值给 cards中的order 就行了。
            const virtualRootNode = {
                topicid: "00000000000", // 特殊的ID或标识符
                topictitle: "所有主题", // 显示的名称
                children: this.topiczu, // 包含所有顶级节点
            };
            this.breadcrumbList = [virtualRootNode];
            this.navigateToFolder(0)
            this.reloadWebflowJs()
            this.ifbianji=false
            this.ifbianjidonghua=false

            //

            var zhuti = JSON.parse(localStorage.getItem("zhuti"));
            if (zhuti) {
                if(zhuti.personalImg){
                    document.getElementById('imgpersonheader').src = zhuti.personalImg;
                    document.getElementById('imgpersonheader').srcset = zhuti.personalImg;

                    // 替换完成之后 将加载中动画状态 none 修改为block   personaljiazai

                }
            }


            document.getElementById("jiazaiyulan").style.display='none'
            document.getElementById("appzhutiye").style.display='block'






        },
        breadInit() {
            var deleteItem = document.getElementById('deleteItem');
            var renameItem = document.getElementById('renameItem');
            var addChildItem = document.getElementById('addChildItem');

            var menu = document.getElementById('globalMenu');

            function hideMenu() {
                menu.style.display = 'none';
            }

            deleteItem.addEventListener('click', hideMenu);
            renameItem.addEventListener('click', hideMenu);
            addChildItem.addEventListener('click', hideMenu);
// 重新挂载菜单动作
            document.querySelectorAll('.image-6').forEach(item => {
                item.addEventListener('click', function (e) {
                    e.stopPropagation(); // 阻止事件冒泡
                    const menu = document.getElementById('globalMenu');

                    const rect = e.target.getBoundingClientRect();
                    menu.style.top = `${rect.bottom + window.scrollY}px`;
                    menu.style.left = `${rect.left + window.scrollX}px`;

                    menu.style.display = 'block';
                });
            });


            document.addEventListener('click', function (e) {
                const menu = document.getElementById('globalMenu');
                if (!menu.contains(e.target)) {
                    menu.style.display = 'none';
                }
            });
        },
        reloadWebflowJs() {


// 点击菜单任意项目，隐藏菜单

            // 使用querySelector直接查找含有webflow.js的<script>标签
            // var script = document.querySelector('script[src*="webflow.js"]');
            // if (script) {
            //     script.parentNode.removeChild(script);
            // }
            //
            // // 创建新的<script>标签并设置src属性，包含时间戳防止缓存
            // var newScript = document.createElement('script');
            // newScript.type = 'text/javascript';
            // newScript.src = 'http://'+requesturlfront+'/js/webflow.js' + '?v=' + new Date().getTime();
            // newScript.onload = function() {
            //     console.log('Webflow JS has been reloaded.');
            //
            //     // 确保Webflow对象存在，然后重新初始化交互效果
            //     if (typeof Webflow !== 'undefined' && Webflow.require('ix2').init) {
            //         Webflow.require('ix2').init();
            //     }
            // };
            // document.head.appendChild(newScript);
        },
        async fetchData1() {


            try {
                const response = await axios.get(`${requesturl}/token_ret`);
                const token = response.data.token;
                axios.defaults.headers.common['Authorization'] = `${token}${this.uid}`;
            } catch (error) {
                console.error('Error fetching the token:', error);
            }
            return new Promise((resolve, reject) => {
                try {
                    const query = {
                        query: {
                            bool: {
                                must: [{match: {uid: localStorage.getItem('uid')}}]
                            }
                        },
                        size: 100
                    };

                    axios.post(requesturl+'/proxy-search', query)
                        .then(async response => {
                            console.log("Response: ", response);

                            const cards = {};
                            response.data.hits.hits.forEach(hit => {
                                const cardData = hit._source;
                                const key = cardData.front.split('：')[0];
                                const front = cardData.front.split('：')[1];
                                if (!cards[key]) cards[key] = {order: "", previewCards: []};
                                cardData.front = front;
                                cardData.back = cardData.back;
                                cardData.mark = cardData.known;
                                delete cardData.known;
                                cardData.id = cardData.sqlId;
                                delete cardData.sqlId;
                                cardData.time = cardData.createtime;
                                delete cardData.createtime;
                                cardData.updatetime = cardData.lastmodifieddate;
                                delete cardData.lastmodifieddate;
                                delete cardData.uid;
                                delete cardData.type;
                                cards[key].previewCards.push(cardData);
                            });



                            localStorage.setItem('cards', JSON.stringify(cards));
                            this.cardsTurn2cards2es()
                            console.log("Updated cards: ", cards);
                            await this.updateCardsOrderFromZhuti();

                            resolve(); // 成功解决 Promise
                        })
                        .catch(error => {
                            console.error('查询失败:', error);
                            reject(error); // 在错误情况下拒绝 Promise
                        });
                } catch (error) {
                    console.error('异常错误:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },

        cards2es2cards(){

            const cards2es=  localStorage.getItem('cards2es') ? JSON.parse(localStorage.getItem('cards2es')) : {};

            if (cards2es&& typeof cards2es=== 'object') {
                Object.keys(cards2es).forEach(key=> {
                    let card = cards2es[key];

                    if (card.previewCards !== undefined) {
                        card.previewCards.forEach(cardData => {
                            const key = cardData.front.split('：')[0];
                            const front = cardData.front.split('：')[1];
                            if (!cards2es[key]) cards2es[key] = {order: "", previewCards: []};
                            cardData.front = front;
                            cardData.back = cardData.back;
                            cardData.mark = cardData.known;
                            delete cardData.known;
                            cardData.id = cardData.sqlId;
                            delete cardData.sqlId;
                            cardData.time = cardData.createtime;
                            delete cardData.createtime;
                            cardData.updatetime = cardData.lastmodifieddate;
                            delete cardData.lastmodifieddate;
                            delete cardData.uid;
                            delete cardData.type;

                        })

                    }


                });
                localStorage.setItem('cards', JSON.stringify(cards2es));
            }

        },

        cardsTurn2cards2es() {
            const cards1 = JSON.parse(localStorage.getItem('cards'));
            if (cards1 && typeof cards1 === 'object') {
                Object.keys(cards1).forEach(key => {
                    let card = cards1[key];
                    //如果card下的previewCards不存在
                    if (card.previewCards !== undefined) {
                        card.previewCards.forEach(previewCard => {
                            if ('front' in previewCard) previewCard.front = key + '：' + previewCard.front;
                            ;
                            if ('mark' in previewCard) {
                                previewCard.known = previewCard.mark;
                                delete previewCard.mark;
                            }
                            ;
                            if ('id' in previewCard) {
                                previewCard.sqlId = previewCard.id;
                                delete previewCard.id;
                            }
                            ;
                            if ('time' in previewCard) {
                                previewCard.createtime = previewCard.time;
                                delete previewCard.time;
                            }
                            ;
                            if ('updatetime' in previewCard) {
                                previewCard.lastmodifieddate = previewCard.updatetime;
                                delete previewCard.updatetime;
                                delete previewCard.icon;
                                delete previewCard.size;
                            }
                            ;previewCard.uid = this.uid;
                            previewCard.type = 1;

                        });
                    }
                });
                localStorage.setItem('cards2es', JSON.stringify(cards1))
            }
        }
        ,
        updateCardsOrderFromZhuti() {
            return new Promise((resolve, reject) => {
                try {
                    const zhutiStorage = localStorage.getItem('zhuti');
                    const dangqianzhuti = localStorage.getItem('dangqianzhuti');
                    let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                    if (zhutiStorage && dangqianzhuti) {
                        const zhuti = JSON.parse(zhutiStorage);
                        if (zhuti && zhuti.topics) {
                            zhuti.topics.forEach(topic => {
                                if (topic.topictitle === dangqianzhuti) {
                                    // 确保cards中有对应的键
                                    if (!cards[dangqianzhuti]) {
                                        cards[dangqianzhuti] = {};
                                    }
                                    cards[dangqianzhuti].order = topic.order;
                                }
                            });
                        }

                        localStorage.setItem('cards', JSON.stringify(cards));
                    }

                    resolve(); // 解决 Promise
                } catch (error) {
                    console.error('Error:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },

        // watch: {
        //     // 监听breadcrumbList的变化
        //     breadcrumbList(newValue) {
        //         if (newValue && newValue.length > 0) {
        //             // 如果breadcrumbList不为空，则获取第一个元素的children
        //             const childrenToSave = newValue[0].children;
        //             // 序列化children并保存到localStorage
        //             localStorage.setItem('zhuti', JSON.stringify(childrenToSave));
        //         }
        //     },
        // },
        initSuoyouKapian() {
            // 创建一个虚拟主题名称，用于表示所有卡片
            const virtualTopicName = "所有卡片";

            // 尝试从localStorage中获取cards
            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};

            // 创建一个新的previewCards数组，用于存放所有卡片
            let allPreviewCards = [];

            // 遍历cards中的每个主题，将其previewCards合并到allPreviewCards中1
            Object.keys(cards).forEach(key => {
                if (key === "所有卡片") return;
                const topic = cards[key];
                if (topic && topic.previewCards) {
                    allPreviewCards = allPreviewCards.concat(topic.previewCards);
                }
            });

            // 创建虚拟主题，并将所有卡片的数组赋值给它
            const virtualTopic = {
                order: '', // 虚拟主题可以没有顺序
                previewCards: allPreviewCards
            };

            // 将虚拟主题添加到cards对象中
            cards[virtualTopicName] = virtualTopic;

            // 更新localStorage
            this.saveTopicNameToCards(cards)
            localStorage.setItem('cards', JSON.stringify(cards));
        },
        saveTopicNameToCards(cards){
            Object.keys(cards).forEach(topicName => {
                if(topicName==='所有卡片')return;
                if(cards[topicName].previewCards===undefined)return;
                cards[topicName].previewCards.forEach(card => {
                    card.topicname = topicName; // 给卡片添加所属主题名称
                });
            });
        },
    },
    mounted() {
        localStorage.removeItem("cards")
        localStorage.removeItem("zhuti")
        var self = this
        const uid = localStorage.getItem('uid');
        if (uid) {
            this.uid = uid
        } else {

            Swal.fire({
                title: '未登录',
                text: '即将跳转登录页面，推荐使用微信扫码登录',
                icon: 'info',
                confirmButtonText: '好的'
            }).then((result) => {
                if (result.value) {
                    window.location.href = '/loginorregistry'; // 这里的 '/login' 是你希望跳转到的URL
                }
            });
        }

        this.fetchData1().then(() => {
            this.fetchAndStoreZhuti1().then(() => {
                this.pageInit()
            })
            this.pageInit()
        })
        //
        this.dangqianzhuti = localStorage.getItem('dangqianzhuti');


    }
});


async function push2es() {
    let xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
    if (!xinzengids.length) return;
    // 复制待新增的ID列表
    const idsToAdd = [...xinzengids];
    console.log("待批量新增的卡片IDs: ", idsToAdd);
    const cards2es = JSON.parse(localStorage.getItem('cards2es'));
    console.log("🚀 ~ file: cardperform.html ~ line 442 ~ cards2es: ", cards2es);
    let bulkBody = '';
    const now = new Date().getTime();

    Object.keys(cards2es).forEach(key => {
        console.log("🚀 ~ file: cardperform.html ~ line 447 ~ key: ", cards2es[key].previewCards);
        if(cards2es[key].previewCards!=undefined && key!='所有卡片'){
            cards2es[key].previewCards.forEach(card => {
                console.log("🚀 ~ file: cardperform.html ~ line 449 ~ card: ", card);
                // 从ids字符数组中拿到待新增的数组内容，
                if (idsToAdd.includes(card.sqlId)) {
                    bulkBody += JSON.stringify({index: {_index: 'users', _type: '_doc', _id: card.sqlId}}) + '\n';
                    bulkBody += JSON.stringify(card) + '\n';
                }
            });
        }
    });

    if (bulkBody) {
        console.log("🚀 ~ file: cardperform.html ~ line 459 ~ bulkBody: ", bulkBody);
        axios.post(requesturl+'/proxy-bulk', bulkBody, {
            headers: {'Content-Type': 'application/x-ndjson'}
        }).then(response => {
                console.log('Bulk operation successfully executed', response.data);
                // 从xinzengids数组中移除已新增的IDs
                xinzengids = xinzengids.filter(id => !idsToAdd.includes(id));
                localStorage.setItem('xinzengids', JSON.stringify(xinzengids));
            }
        ).catch(error => console.error('Failed to execute bulk operation', error));
    }
}

// 定时任务
setInterval(push2es, 1000 * 20 ); // 每3分钟执行一次




// 修改后的deleteEsIds方法
async function deleteEsIds() {
    let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];
    if (!shanchu.length) return;

    // 复制待删除的ID列表
    const idsToDelete = [...shanchu];
    console.log("🚀 ~ file: cardperform.html ~ line 594 ~ idsToDelete: ", idsToDelete);
    //从localstorage中获取xinzengids
    const xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
    let bulkDeleteBody = '';
    idsToDelete.forEach(id => {
        //如果xinzengids中包含这个id则不执行删除这个id
        if (xinzengids.includes(id)) {
            console.log('Skipping deletion of ID ' + id + ' because it is in the xinzengids list.');
            return;
        }
        bulkDeleteBody += JSON.stringify({delete: {_index: 'users', _type: '_doc', _id: id}}) + '\n';
    });


    if (bulkDeleteBody) {
        axios.post(requesturl+'/proxy-bulk', bulkDeleteBody, {
            headers: {'Content-Type': 'application/x-ndjson'}
        }).then(response => {
            console.log('Bulk delete operation successfully executed', response.data);
            // 从shanchu数组中移除已删除的IDs
            shanchu = shanchu.filter(id => !idsToDelete.includes(id));
            localStorage.setItem('shanchu', JSON.stringify(shanchu));
        }).catch(error => console.error('Failed to execute bulk delete operation', error));
    }
}

// 设置定时任务，定期调用deleteEsIds
setInterval(deleteEsIds, 1000 * 2); // 比如每两分钟执行一次




function saveZhutiToElasticsearch() {
    const zhuti = localStorage.getItem('zhuti');
    const uid = localStorage.getItem('uid');

    const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
    var maxEditTimeLocalZhuti = localZhuti.topics.length > 0
        ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
        : 0;
    console.log("🚀 ~ 2file: cardzhuye-vue.js ~ line 259 ~ maxEditTimeLocalZhuti: ",maxEditTimeLocalZhuti);
    //获取maxEditTimeZhuti并和maxEditTimeLocalZhuti进行比较，如果maxEditTimeZhuti大于maxEditTimeLocalZhuti，则说明有新的数据需要同步到Elasticsearch
    const maxEditTimeZhuti = localStorage.getItem('maxEditTimeZhuti') || 0;
    console.log("🚀 ~ file: cardzhuye-vue.js ~ line 261 ~ maxEditTimeZhuti: ",maxEditTimeZhuti);
    if (maxEditTimeZhuti < maxEditTimeLocalZhuti) {

        if (zhuti && uid) {
            const data = {
                id: uid,
                zhuti: zhuti
            };

            axios.post(requesturl+'/proxy-user-order-cud', data).then(response => {
                console.log('Data successfully saved to Elasticsearch', response.data);
                //更新maxEditTimeZhuti
                localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
            }).catch(error => {
                console.error('Failed to save data to Elasticsearch', error);
            });

        }
    } else {
        console.log("no new zhuti data to save")
    }
}

// 设置定时任务，每5分钟执行一次
setInterval(saveZhutiToElasticsearch, 20000);

// document.getElementById('syncButton').addEventListener('click', function() {
//     saveZhutiToElasticsearch();
// });
// 你可以使用beforeunload事件来监控页面退出的动作,成功了，关闭的时候执行发送了。
window.addEventListener('beforeunload', function (event) {
    // 在这里编写你的函数代码
    saveZhutiToElasticsearch()
});


//tinymce模块

function tinymcechushihuamyTextarea(idString,sfjixu) {
    var globalFunctionRequestReplaceExpressProxy="http://baota.memlee.top:4000"
    var imageCompression = function(base64, w){
        return new Promise(function(resolve, reject) {
            console.log("enter promise")
            var newImage = new Image();
            var quality = 0.6;
            console.log("压缩前",imgPasteUrl.length/1024)
            newImage.src = imgPasteUrl;
            newImage.setAttribute("crossOrigin", 'Anonymous');
            var imgWidth, imgHeight;
            newImage.onload = function () {
                imgWidth = this.width; imgHeight = this.height;
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                if (Math.max(imgWidth, imgHeight) > w)
                {if (imgWidth > imgHeight)
                {canvas.width = w; canvas.height = w * imgHeight / imgWidth;}
                else
                {canvas.height = w; canvas.width = w * imgWidth / imgHeight;}
                }
                else
                {canvas.width = imgWidth; canvas.height = imgHeight; }
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
                var base64 = canvas.toDataURL("image/jpeg", quality);
                if (base64.length / 1024 > 1024) {
                    quality = (1024-200)/(base64.length / 1024)
                    base64 = canvas.toDataURL("image/jpeg", quality);
                }
                if (base64.length / 1024 < 50) {
                    quality = 50+20/(base64.length /1024 )
                    base64 = canvas.toDataURL("image/jpeg", quality);
                }
                resolve(base64);
            }
        })
    }
    var imgPasteUrl = ""   //全局变量用于存储上传图片路径
    function uploadImg2Gitee(img, success, failure,loadingNotification) {
        var base64 = img.split(",")[1];
        var requesturl1 =
            "https://jr9nqpz4-8083.asse.devtunnels.ms"
        // $.ajax({
        //     //requesturl+"upload-image-gitee"、upload_image_to_oss
        //     // url: requesturl+"/upload-image-gitee",  // 更改为后端新建的路由 之前的方式
        //     url: requesturl+"/upload_image_to_oss",  // 更改为后端新建的路由
        //     type: "post",
        //     data: JSON.stringify({"content": base64}),
        //     dataType: 'json',
        //     processData: false,
        //     async: false,
        //     contentType: "application/json;charset=UTF-8",
        //     success: function(data) {
        //         var imgSrc = data.imgSrc;  // 使用后端返回的imgSrc
        //         loadingNotification.close()
        //         success(imgSrc);
        //     },
        //     error: function(e) {
        //         alert("上传图片失败");
        //         loadingNotification.close()
        //         console.log(e);
        //         failure(e);
        //     }
        // });

        const url = `${requesturl}/upload_image_to_oss`;
        const data = JSON.stringify({ "content": base64 });

        axios.post(url, data, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                const imgSrc = response.data.imgSrc; // 使用后端返回的imgSrc
                loadingNotification.close();
                success(imgSrc); // 假设这是成功回调函数
            })
            .catch(error => {
                alert("上传图片失败");
                loadingNotification.close();
                console.log(error);
                failure(error); // 假设这是失败回调函数
            });



    }
    var ifInline = false;
    if(sfjixu==3){
        ifInline=true
    }
    // 在这里编写函数的代码
    tinymce.init({
        selector: idString, // 指定要初始化的<textarea>元素的ID
        inline: ifInline,
        mobile: {
            menubar: true
        },
        language_url: requesturl+'/static/tinymce-lang-zh@5.2.2.js', // 指定语言文件的URL https://cdn.jsdelivr.net/gh/wt-sml/wutong_cdn/js/tinymce-lang-zh@5.2.2.js
        language: 'zh_CN', // 设置语言为中文
        skin_url: requesturl+'/static/skin.min.css', // 指定皮肤文件的URL
        height: 400, // 设置编辑器高度
        plugins: [
            "advlist autolink lists link image axupimgs charmap preview hr anchor",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime nonbreaking save table contextmenu directionality",
            "emoticons paste textcolor colorpicker textpattern code lineheight"
        ],
        content_style: 'img {  max-width: 100%;  height: auto; }',
        textpattern_patterns: [
            {start: '*', end: '*', format: 'italic'},
            {start: '**', end: '**', format: 'bold'},
            {start: '#', format: 'h1'},
            {start: '##', format: 'h2'},
            {start: '###', format: 'h3'},
            {start: '####', format: 'h4'},
            {start: '#####', format: 'h5'},
            {start: '######', format: 'h6'},
            {start: '1. ', cmd: 'InsertOrderedList'},
            {start: '* ', cmd: 'InsertUnorderedList'},
            {start: '- ', cmd: 'InsertUnorderedList'},
            {start: '//brb', replacement: 'Be Right Back'}
        ],
        toolbar:
            'image axupimgs  | undo redo | bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | link unlink code | removeformat',
        branding: false,
        menubar: true,
        images_upload_handler: async (blobInfo, success, failure) => {
            // 显示正在加载的提示

            const loadingNotification = tinymce.get(idString.replace(/#/g, "")).notificationManager.open({
                text: '正在粘贴图片...',
                type: 'info',
                closeButton: false,
            });
            var img = ""

            if (blobInfo.base64 != undefined) {
                img = 'data:image/jpeg;base64,' + blobInfo.base64()
            } else {
                var asyncReader = function(){
                    return new Promise(function(resolve,reject){
                        const reader = new FileReader();
                        reader.addEventListener('load', async () => {
                            img = reader.result + ''
                            //在这里使用压缩算法
                            imgPasteUrl = img
                            img = await imageCompression(img, 1400)
                            console.log("压缩后", img.length / 1024);
                            resolve(img)
                        });
                        reader.readAsDataURL(blobInfo.blob());
                    })
                }
                img =  await asyncReader()
            }
            if (img != "") {
                imgPasteUrl = img
                img = await imageCompression(img, 1400)
                console.log("压缩后", img.length / 1024);
                console.log("center")
                console.log("end")
            }
            uploadImg2Gitee(img, success, failure,loadingNotification);



        },
        paste_data_images: true,
        paste_preprocess: async function (plugin, args) {
        },
        images_upload_credentials: true,
        images_reuse_filename: true,
        image_advtab: true,
        images_upload_base_path: '',
        images_upload_url: 'doFileUpload.asp',
        automatic_uploads: true,
        file_picker_types: 'file, image, media',
        file_picker_callback: function (callback, value, meta) {
        },
        images_dataimg_filter: function (img) {
            //可以在这里把文件上传，使用全局参数保存路径，最后在处理的时候替换img.src实现
            imgPasteUrl = img
            return !img.hasAttribute('internal-blob');  // blocks the upload of <img> elements with the attribute "internal-blob".
        },
        init_instance_callback: function (editor) {
            if(sfjixu===1){
                tinymcechushihuamyTextarea("#myTextareaxinzeng",0)
                const initTinyMCE = localStorage.getItem('initTinyMCE') === 'true';
                if (initTinyMCE) {
                    // document.getElementById('jiazaizhongdonghua').style.display = 'none';
                    // 完成后，重置标志以避免影响后续逻辑
                    localStorage.setItem('initTinyMCE', 'false');
                }
                // document.getElementById('jiazaizhongdonghua').style.display = 'none';
                console.log('TinyMCE 初始化完成');
            }
        }
    });
}


document.addEventListener('DOMContentLoaded', (event) => {
    tinymcechushihuamyTextarea("#myTextarea", 1)
})


// 你可以使用beforeunload事件来监控页面退出的动作,成功了，关闭的时候执行发送了。
window.addEventListener('beforeunload', function (event) {
    // 在这里编写你的函数代码
    push2es()
    deleteEsIds()
    saveZhutiToElasticsearch()
});

document.addEventListener('DOMContentLoaded', function() {
    var zhuti = JSON.parse(localStorage.getItem("zhuti"));
    if (zhuti.personalImg) {
        document.getElementById('uploadedImage').src = zhuti.personalImg;
        document.getElementById('imgpersonheader').src = zhuti.personalImg;
        document.getElementById('imgpersonheader').srcset = zhuti.personalImg;
    }
});




